package com.cskaoyan.market.controller.admin;

import com.cskaoyan.market.db.domain.MarketOrder;
import com.cskaoyan.market.service.MarketOrderService;
import com.cskaoyan.market.service.impl.MarketOrderServiceImpl;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("admin/order")
public class OrderController {
    @Autowired
    private MarketOrderService marketOrderService;

    @GetMapping("detail")
    private void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        Map<String, Object> marketOrders = marketOrderService.readOrderDetail(id);

        if (marketOrders.size() > 0) {
            Object ok = ResponseUtil.ok(marketOrders);
            ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
            String s = objectMapper.writeValueAsString(ok);
            resp.getWriter().println(s);
        } else {
            Object fail = ResponseUtil.fail();
            ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
            String s = objectMapper.writeValueAsString(fail);
            resp.getWriter().println(s);
        }

    }


    //    订单状态对应的状态码
//101: '未付款', 102: '用户取消', 103: '系统取消', 201: '已付款',
// 202: '申请退款', 203: '已退款', 301: '已发货', 401: '用户收货', 402: '系统收货'
    @GetMapping("list")
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        String page = req.getParameter("page");
//        String limit = req.getParameter("limit");
//        String[] orderStatusArrays = req.getParameterValues("orderStatusArray");
//        String[] timeArrays = req.getParameterValues("timeArray");
//
//        String sort = req.getParameter("sort");
//        String order = req.getParameter("order");
////        String start = req.getParameter("start");
////        String end = req.getParameter("end");
//        String orderId = req.getParameter("orderId");
//        String userId = req.getParameter("userId");
//        String orderSn = req.getParameter("orderSn");
//        List<MarketOrder> marketOrders = marketOrderService.readOrderList(page, limit, sort, order, orderId, userId, orderSn, timeArrays, orderStatusArrays);
//        Object ok = ResponseUtil.okList(marketOrders);
//        //相应体
//
//        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
//        String s = objectMapper.writeValueAsString(ok);
//        resp.getWriter().println(s);
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String startParam = req.getParameter("start");
        String endParam = req.getParameter("end");
        String userIdParam = req.getParameter("userId");
        String orderIdParam = req.getParameter("orderId");
        String orderSn = req.getParameter("orderSn");
        String[] orderStatusArrays = req.getParameterValues("orderStatusArray");
        int page = 0;
        int limit = 0;
        int userId=0;
        int orderId=0;
        LocalDateTime start = null;
        LocalDateTime end = null;
        ArrayList<Short> orderStatus = new ArrayList<>();


// 缺少必要参数，返回响应：参数错误
        if (StringUtils.isEmpty(pageParam) || StringUtils.isEmpty(limitParam)) {
            resp.getWriter().println(
                    JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument())
            );
        }

// sort若为空，则取默认值add_time
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
// order若为空，则取默认值desc - 降序
        if (StringUtils.isEmpty(order)) {
            order = "desc";
        }

// 参数转换 - 若非空，startStr(String)转为start(LocalDateTime)
// 2022-07-15 21:00:20
        if (!(StringUtils.isEmpty(startParam) || StringUtils.isEmpty(endParam))) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            start = LocalDateTime.parse(startParam, formatter);
            end = LocalDateTime.parse(endParam, formatter);
        }
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
            if (userIdParam!=null){
                userId = Integer.parseInt(userIdParam);
            }
            if (orderIdParam!=null){
                orderId = Integer.parseInt(orderIdParam);
            }
            if (orderStatusArrays != null && orderStatusArrays.length > 0) {
                for (String s : orderStatusArrays) {
                    orderStatus.add(Short.valueOf(s));
                }
            }
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }

        List<MarketOrder> list = marketOrderService.list(page, limit, sort, order, start, end, userId, orderId, orderSn, orderStatus);

        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(list)));
    }

    @GetMapping("channel")
    private void channel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().println(marketOrderService.getChannel());
    }
    @PostMapping("delete")
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String orderId = JacksonUtil.parseString(requestBody, "orderId");
        int i = marketOrderService.deleteOrder(orderId);
        Object res = null;
        if (i > 0) {
            res = ResponseUtil.ok();
        } else {
            res = ResponseUtil.fail();
        }
        System.out.println(i);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(res);
        resp.getWriter().println(s);
    }
    @PostMapping("refund")
    private void refund(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String orderId = JacksonUtil.parseString(requestBody, "orderId");
        System.out.println(orderId);
        int i = marketOrderService.refundOrder(orderId);
        System.out.println(i);
        Object res = null;
        if (i > 0) {
            res = ResponseUtil.ok();
        } else {
            res = ResponseUtil.fail();
        }
        System.out.println(i);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(res);
        resp.getWriter().println(s);
    }
    @PostMapping("ship")
    private void ship(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String requestBody = HttpUtil.getRequestBody(req);
        String orderId = JacksonUtil.parseString(requestBody, "orderId");
        String shipChannel = JacksonUtil.parseString(requestBody, "shipChannel");
        String shipSn = JacksonUtil.parseString(requestBody, "shipSn");
        System.out.println(orderId+shipChannel+shipSn);
        int i = marketOrderService.ShipOrder(orderId, shipChannel, shipSn);
        System.out.println(i);
        Object res = null;
        if (i > 0) {
            res = ResponseUtil.ok();
        } else {
            res = ResponseUtil.fail();
        }
        System.out.println(i);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(res);
        resp.getWriter().println(s);
    }
}
